package io.gitee.caoxiaoyu97.log.dynamic.level;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/*********************************************************
 * 文件名称：LogDynamicLevelEnhancer.java
 * 系统名称：bfts
 * 模块名称：com.hundsun.tbsp.bfts.other.base.log
 * 功能说明：
 * 开发人员 @author：caoxy31978
 * 开发时间 @date：2025/9/23 14:17
 * 修改记录：程序版本  修改日期  修改人员  修改单号  修改说明
 *********************************************************/
public abstract class LogDynamicLevelEnhancer {

    private static final Map<String, String> SYSTEMS;
    static {
        Map<String, String> systems = new LinkedHashMap();
        systems.put("ch.qos.logback.core.Appender", "com.hundsun.tbsp.bfts.other.base.log.logback.LogBackLogDynamicLevelEnhancer");
        systems.put("org.apache.logging.log4j.core.impl.Log4jContextFactory", "com.hundsun.tbsp.bfts.other.base.log.log4j.Log4jLogDynamicLevelEnhancer");
        SYSTEMS = Collections.unmodifiableMap(systems);
    }
    private static volatile LogDynamicLevelEnhancer logDynamicLevelEnhancer;

    protected abstract void enhance();
    public static void init(){
        LogDynamicLevelEnhancer enhancer = getLogDynamicLevelEnhancer();
        enhancer.enhance();
    }

    private static LogDynamicLevelEnhancer getLogDynamicLevelEnhancer() {
        if (logDynamicLevelEnhancer != null){
            return logDynamicLevelEnhancer;
        }
        synchronized (LogDynamicLevelEnhancer.class) {
            if (logDynamicLevelEnhancer != null){
                return logDynamicLevelEnhancer;
            }
            for (Map.Entry<String, String> entry : SYSTEMS.entrySet()) {
                if (isClassPresent(entry.getKey())){
                    try {
                        Class<?> clazz = Class.forName(entry.getValue());
                        LogDynamicLevelEnhancer enhancer = (LogDynamicLevelEnhancer) clazz.newInstance();
                        logDynamicLevelEnhancer = enhancer;
                        break;
                    } catch (Exception e) {
                    }
                }
            }
            if (logDynamicLevelEnhancer == null){
                logDynamicLevelEnhancer = new NoneLogDynamicLevelEnhancer();
            }
        }
        return logDynamicLevelEnhancer;
    }

    private static boolean isClassPresent(String className) {
        try {
            Class.forName(className);
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
    static class NoneLogDynamicLevelEnhancer extends LogDynamicLevelEnhancer {
        @Override
        protected void enhance() {
        }
    }
}
